package com.galeno.blink.demo;

import com.galeno.FlinkUtils;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author galeno
 * @Title:
 * @Description:
 * @date 2021/10/1920:12
 */
public class StartNewChainDemo {
    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port",8888);
        StreamExecutionEnvironment locEnvWebUI = FlinkUtils.getLocEnvWebUI(configuration);
        DataStreamSource<String> lines = locEnvWebUI.socketTextStream("192.168.77.101", 8888);
        SingleOutputStreamOperator<String> upper = lines.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String in, Collector<String> out) throws Exception {
                String[] words = in.split("\\s+");
                for (String word : words) {
                    out.collect(word.toUpperCase());
                }
            }
        }).disableChaining();
        SingleOutputStreamOperator<String> outa = upper.filter(new FilterFunction<String>() {
            @Override
            public boolean filter(String s) throws Exception {
                return !s.contains("a");
            }
        }).startNewChain();
        SingleOutputStreamOperator<Tuple2<String, Integer>> tupled = outa.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String s) throws Exception {
                return Tuple2.of(s, 1);
            }
        });
        KeyedStream<Tuple2<String, Integer>, String> keyed = tupled.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            @Override
            public String getKey(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
                return stringIntegerTuple2.f0;
            }
        });
        SingleOutputStreamOperator<Tuple2<String, Integer>> sumed = keyed.sum(1);
        sumed.print();
        locEnvWebUI.execute();

    }

}
